const element = document.documentElement

element.addEventListener('mousedown', event => {
  start(event)

  const mousemove = event => {
    move(event)
  }
  const mouseup = event => {
    end(event)
    element.removeEventListener('mousemove', mousemove)
    element.removeEventListener('mouseup', mouseup)
  }
  element.addEventListener('mousemove', mousemove)
  element.addEventListener('mouseup', mouseup)
})

element.addEventListener('touchstart', event => {
  for (let touch of event.changedTouches) {
    start(touch)
  }
})
element.addEventListener('touchmove', event => {
  for (let touch of event.changedTouches) {
    move(touch)
  }
})
element.addEventListener('touchend', event => {
  for (let touch of event.changedTouches) {
    end(touch)
  }
})
element.addEventListener('touchcancel', event => {
  for (let touch of event.changedTouches) {
    cancel(touch)
  }
})

let handler = null
let startX = null
let startY = null
let isPan = false
let isTap = true
let isPress = false

const start = ({clientX, clientY}) => {
  startX = clientX
  startY = clientY
  isTap = true
  isPan = false
  isPress = false

  handler = setTimeout(() => {
    isTap = false
    isPan = false
    isPress = true
    handler = null
    console.log('press')
  }, 500)
}
const move = ({clientX, clientY}) => {
  const dx = clientX - startX
  const dy = clientY - startY
  if (!isPan && dx ** 2 + dy ** 2 > 100) {
    isTap = false
    isPan = true
    isPress = false
    clearTimeout(handler)
    console.log('panstart')
  }
  if (isPan) {
    console.log(dx, dy)
    console.log('pan')
  }
}
const end = ({clientX, clientY}) => {
  if (isTap) {
    console.log('tap')
    clearTimeout(handler)
  }
  if (isPan) {
    console.log('panend')
  }
  if (isPress) {
    console.log('pressend')
  }
}
const cancel = ({clientX, clientY}) => {
  clearTimeout(handler)
}